var router = require('koa-router')();
const fs = require('fs');// 引入文件读写模块
const filepath = '../learn-koa/data/data.json';// 指定文件路径.这里要注意下路径,可以看下报错

router.prefix('/users');

router.post('/addUser',function *(next){
  // 获取用户数据
  const _this = this;
  const requestData = this.request.body;
  
  fs.readFile(filepath,'utf-8',(err,data) =>{
    if(err){
        console.log(err);
        console.log('ERROR!Failed to read file!')
    }

    const params = data && JSON.parse(data) || [];
    const newParams = [...params,requestData];

    fs.writeFile(filepath,JSON.stringify(newParams),(err)=>{
      if(err) _this.body = '写入文件失败！';
    })
})
})

module.exports = router;
